package ngram.reader;

import exceptions.NegativeNumberException;
import exceptions.NegativeNumberOrZeroException;
import ngram.util.IOUtil;
import java.io.DataInputStream;
import java.io.IOException;
import org.apache.hadoop.io.file.tfile.Utils;

/**
 * Readers custom n-gram file version 1, where: <br />
 * year = short (2 bytes) <br />
 * volume count = int (4 bytes) <br />
 * match count = int (4 bytes) <br />
 * 
 * @author g1wshimu
 */
public class V2FileReader implements NGramFileReader {

    private final DataInputStream STREAM;

    public V2FileReader(DataInputStream stream) {
        this.STREAM = stream;
    }

    /**
     * 
     * @param reader
     * @return null if the end of file (EOF) is reached.
     * @throws NegativeNumberException if the length of the String is less than 0
     */
    @Override
    public String readNGram() throws IOException, NegativeNumberException {
        return IOUtil.readUtf(STREAM);
    }

    @Override
    public int readYear() throws IOException {
        return STREAM.readShort();
    }

    @Override
    public long readVolumeCount() throws IOException {
        return Utils.readVLong(STREAM);
    }

    @Override
    public long readMatchCount() throws IOException {
        return Utils.readVLong(STREAM);
    }

    public int readHeader() throws IOException,
            NegativeNumberOrZeroException {
        int header = STREAM.readInt();
        NegativeNumberOrZeroException.validate("header", header);
        return header;
    }

    public void skip(int bytes) throws IOException {
        IOUtil.skip(STREAM, bytes);
    }

}
